from urllib import request, parse
from lxml import etree
import ssl


# 取消 https 代理验证
ssl._create_default_https_context = ssl._create_unverified_context


def tencents(self, name):
    # 报头
    user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36'
    headers = {'User-Agent': user_agent}
    # url = "https://v.qq.com/x/search/?q=%E9%99%88%E6%83%85%E4%BB%A4"
    url = "https://v.qq.com/x/search/?q=" + parse.quote(name)
    req = request.Request(url, headers=headers)
    try:
        response = request.urlopen(req)
        # 获取每页的HTML源码字符串
        html = response.read().decode('utf-8')
        # 解析html 为 HTML 文档
        selector = etree.HTML(html)

        # 剧名
        defalut_name = selector.xpath('(//div[@class="_infos"])[1]//a//em/text()')[0]
        # 来源
        source = "腾讯视频"

        # 剧照
        pic = 'https:' + \
              selector.xpath('//div[@class="_infos"][1]//a[@class="figure result_figure"]/img/@src')[0]

        # 导演
        director = selector.xpath(
            '//div[@class="_infos"][1]//div[@class="info_item info_item_even"]//span[@class="content"]/a/text()')
        # 主演
        actor = selector.xpath(
            '//div[@class="_infos"][1]//div[@class="info_item info_item_odd"]//span[@class="content"]/a/text()')

        # 简介
        desc = selector.xpath(
            '//div[@class="_infos"][1]//div[@class="info_item info_item_desc"]//span[@class="desc_text"]/text()')[
            0]

        content_list = selector.xpath('//div[@class="_playlist"][1]//div[@class="item"]//a')
        list = []
        for item in content_list:
            title = item.xpath('text()')[0]
            link = item.xpath('@href')[0]
            list.append({"title": title, "link": link})

        defalut_result = {
            "source": source,
            "name": name,
            "pic": pic,
            "director": director,
            "actor": actor,
            "desc": desc,
            "list": list,
        }

        return defalut_result

    except Exception:
        print(url, Exception)
        data = {"code": -1, "message": "error", "data": None}
        return data
